﻿using System;
using System.Collections.Generic;
using System.Linq;
using DataBaseLayer.Abstractions.Interfaces.Services;
using DataBaseLayer.Dto;

namespace DataBaseLayer.Services
{
	public class NewsService : INewsService
	{
		#region Variables

		private readonly Peresvet _dataBase;

		#endregion

		#region Constructors

		public NewsService(Peresvet dataBase)
		{
			if (dataBase == null)
				throw new ArgumentNullException(string.Format("data base"));
			_dataBase = dataBase;
		}

		#endregion

		#region INewsService Members

		public NewsData GetNewsById(int newsId)
		{
			return _dataBase.News
				.Select(n => new NewsData
				{
					NewsId = n.NewsId,
					ImageUrl = n.Gallery != null && n.Gallery.Images.Any()
						? (n.Gallery.Images.FirstOrDefault(i => i.IsDefault) ?? n.Gallery.Images.FirstOrDefault()).Url
						: string.Empty,
					ThumbImageUrl = n.Gallery != null && n.Gallery.Images.Any()
						? (n.Gallery.Images.FirstOrDefault(i => i.IsDefault) ?? n.Gallery.Images.FirstOrDefault()).UrlThumb
						: string.Empty,
					Description = n.Description,
					Header = n.Header,
					Date = n.Date,
					GalleryId = n.GalleryId
				})
				.SingleOrDefault(n => n.NewsId == newsId);
		}

		public IEnumerable<NewsData> GetNews()
		{
			return _dataBase.News
				.Select(n => new NewsData
				{
					NewsId = n.NewsId,
					ImageUrl = n.Gallery != null && n.Gallery.Images.Any()
						? (n.Gallery.Images.FirstOrDefault(i => i.IsDefault) ?? n.Gallery.Images.FirstOrDefault()).Url
						: string.Empty,
					ThumbImageUrl = n.Gallery != null && n.Gallery.Images.Any()
						? (n.Gallery.Images.FirstOrDefault(i => i.IsDefault) ?? n.Gallery.Images.FirstOrDefault()).UrlThumb
						: string.Empty,
					Description = n.Description,
					Header = n.Header,
					Date = n.Date,
					GalleryId = n.GalleryId
				})
				.OrderByDescending(n => n.Date)
				.ToList();
		}

		public void SaveNews(NewsData entity, int totalNewsCapasity)
		{
			if (entity == null) return;

			var news = entity.NewsId > 0
				? _dataBase.News.SingleOrDefault(n => n.NewsId == entity.NewsId)
				: new News();
			if (news == null) return;

			news.Header = entity.Header;
			news.Description = entity.Description;
			news.GalleryId = entity.GalleryId;
			news.Date = entity.Date;

			if (news.NewsId == 0)
			{
				if (_dataBase.News.Count() >= totalNewsCapasity)
				{
					var delNews = _dataBase.News.OrderByDescending(n => n.Date).Skip(totalNewsCapasity - 1).ToList();
					foreach (var item in delNews)
					{
						_dataBase.News.Remove(item);
					}
				}

				_dataBase.News.Add(news);
			}
			_dataBase.SaveChanges();
		}

		public void DeleteNews(int id)
		{
			var news = _dataBase.News.SingleOrDefault(n => n.NewsId == id);
			if (news == null) return;

			_dataBase.News.Remove(news);
			_dataBase.SaveChanges();
		}

		#endregion
	}
}
